import React from 'react';
import {
    Tabs, Button, message, Select,
    Typography, Input, Form, Spin
} from 'antd';
import {
    LoadingOutlined
} from '@ant-design/icons';
import { connect } from 'umi';
import moment from 'moment';
import request from '@/utils/request';
import MyDataTable from '@/components/MyDataTable';

const { Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;
class ViewPage extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            loading2: true,
            freshNum: 0,
            pageIndex: 1,
            pageSize: 10,
            dataSource: [],
            partItems: []
        }
    }
    formRef: any = React.createRef();
    componentDidMount() {
        this.fetchDatas();
        const { currentUser } = this.props;
        this.formRef.current.setFieldsValue({
            assignedPersonId: currentUser.id,
            description: "MRP task run",
            title: "MRP Task",
            state: 0
        });
        this.fetchPart();
    }
    fetchPart = (keywords: string = '') => {
        this.setState({ fetching: true })
        request('/api/services/app/Part/GetList', {
            method: 'GET',
            params: {
                skipCount: 0,
                maxResultCount: 10,
                keywords
            },
        }).then((response) => {
            if (response && response.result) {
                this.setState({ partItems: response.result.items, loading2: false, fetching: false })
            }
        });
    }
    fetchDatas = () => {
        this.setState({ loading: true });
        this.props.dispatch({
            type: "Abp/getList",
            control: 'MRPTask',
        }).then(() => {
            var resp = this.props.response;
            if (resp) {
                this.setState({
                    dataSource: resp.result,
                    loading: false,
                });
            }
        });
    }
    setCurrent = (obj?: any) => {
        if (this.props.setCurrent) {
            this.props.setCurrent(obj);
        }
    }
    onSearch = (keywords: string) => {
        let _this = this;
        this.setState({ keywords }, function () {
            _this.fetchDatas()
        })
    };
    onFinish = (values: any) => {
        // if (!values.jobNum && !values.partNum) {
        //     message.warning('工单号和物料编码至少填写一项');
        //     return;
        // }
        let d = {
            jobNum: values.jobNum,
            partNum: values.partNum
        }
        let obj = {
            title: values.title,
            description: values.description,
            taskArgs: JSON.stringify(d)
        }
        console.log(obj);
        request('/api/services/app/MRPTask/CreateTask', {
            method: 'POST',
            data: obj,
        }).then((response) => {
            if (response && response.result > 0) {
                message.success('任务创建成功')
                this.fetchDatas()
                this.runMRP(values)
            }
        });
    };
    runMRP = (values: any) => {
        var data = {
            jobNum: values.jobNum,
            partNum: values.partNum
        }
        request('/api/services/app/MRPService/RunMRP', {
            method: 'POST',
            data,
        })
    }

    onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    refreshTask = () => {
        const { freshNum } = this.state;
        this.setState({ freshNum: freshNum + 1 })
    }
    render() {
        const { partItems, loading2, fetching, freshNum } = this.state;
        const columns = [
            {
                title: '任务名称',
                dataIndex: 'title',
                key: 'title',
                width: 100,
            },
            {
                title: '创建时间',
                dataIndex: 'creationTime',
                key: 'creationTime',
                render: (text: any) => (
                    <span><Text type="secondary">{moment(text).format('YYYY-MM-DD hh:mm:ss')}</Text></span>
                )
            },
            {
                title: '结束时间',
                dataIndex: 'endTime',
                key: 'endTime',
                render: (text: any) => (
                    <span><Text type="secondary">{moment(text).format('YYYY-MM-DD hh:mm:ss')}</Text></span>
                )
            },
            {
                title: '耗时',
                dataIndex: 'runTimes',
                key: 'runTimes',
                width: 100,
                render: (text: any) => (
                    <span>{text} s</span>
                )
            },
            {
                title: '状态',
                width: 100,
                render: (record: any) =>
                    <span>{record.state === 0 ? <LoadingOutlined /> : '已完成'}</span>
            },
        ];
        const children: any = []
        partItems.forEach((element: any) => {
            children.push(<Option key={element.id} value={element.partNum} >{element.partNum} {element.searchWord}</Option>);
        });
        return (
            <>
                <Tabs defaultActiveKey="1">
                    <TabPane tab="创建任务" key="1">
                        <Spin spinning={loading2}>
                            <Form
                                name="basic"
                                labelCol={{ span: 5 }}
                                wrapperCol={{ span: 14 }}
                                initialValues={{ remember: true }}
                                onFinish={this.onFinish}
                                onFinishFailed={this.onFinishFailed}
                                ref={this.formRef}
                            >
                                <Form.Item
                                    label="名称"
                                    name="title"
                                    rules={[{ required: true, message: 'Please input your username!' }]}
                                >
                                    <Input disabled />
                                </Form.Item>

                                <Form.Item
                                    label="任务描述"
                                    name="description"
                                    rules={[{ required: true, message: 'Please input your password!' }]}
                                >
                                    <Input disabled />
                                </Form.Item>
                                <Form.Item
                                    label="工单号"
                                    name="jobNum"
                                >
                                    <Input />
                                </Form.Item>
                                <Form.Item
                                    label="物料编码"
                                    name="partNum"
                                >
                                    <Select
                                        //showSearch
                                        mode="multiple"
                                        allowClear
                                        style={{ width: '100%' }}
                                        placeholder="请选择物料编码"
                                        onSearch={this.fetchPart}
                                        notFoundContent={fetching ? <Spin size="small" /> : null}
                                    >
                                        {children}
                                    </Select>
                                </Form.Item>
                                <Form.Item wrapperCol={{ offset: 5, span: 14 }}>
                                    <Button type="primary" htmlType="submit">
                                        创建
                                    </Button>
                                </Form.Item>
                            </Form>
                        </Spin>
                    </TabPane>
                    <TabPane tab="任务列表" key="2">
                        <div style={{ marginBottom: 16,textAlign:'right' }}>
                            <Button type="primary" size="middle" onClick={this.refreshTask}>刷新任务</Button></div>
                        <MyDataTable act="GetAll" columns={columns} pageSize={5} size="small" freshNum={freshNum} control="MRPTask" />
                    </TabPane>
                </Tabs>

            </>
        )
    }
}
export default connect(({ Abp, user }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: user.currentUser,
}))(ViewPage);